package com.yy.ant.chat.controller;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import com.yy.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.tio.core.Tio;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yy.ant.chat.entity.Flock;
import com.yy.ant.chat.entity.Flockrefuser;
import com.yy.ant.chat.entity.Friends;
import com.yy.ant.chat.entity.Message;
import com.yy.ant.chat.entity.Messages;
import com.yy.ant.chat.service.IFlockService;
import com.yy.ant.chat.service.IFlockrefuserService;
import com.yy.ant.chat.service.IFriendsService;
import com.yy.ant.chat.service.IMessageService;
import com.yy.ant.sys.entity.User;
import com.yy.ant.sys.service.IUserService;
import com.yy.model.ResultMsg;
import com.yy.model.ResultTable;
import com.yy.model.enums.ResultEnum;
import com.yy.utils.SessionUtil;

/**
 * <p>
 * 加群消息 前端控制器
 * </p>
 *
 * @author liyingying
 * @since 2020-01-06
 */
@RestController
@RequestMapping("/chat/message")
public class MessageController {

	@Autowired
	private IMessageService iMessageService;

	@Autowired
	private IFriendsService iFriendsService;
	@Autowired
	private IFlockService iFlockService;
	@Autowired
	private IUserService iUserService;
	@Autowired
	private IFlockrefuserService iFlockrefuserService;
	
	@Value("${yy.touxiang}")
	private String url;
	/**
	 * 根据用户ID 初始化群组数据
	 *
	 * @return
	 */
	@RequestMapping(value = "/unreadMsgCount")
	public HashMap<String, Object> unreadMsgCount(@RequestHeader("token") String token) {
		ResultMsg resultMsg1= JwtUtils.validateJWT(token);
		if (!resultMsg1.isSuccess()){
			return null;
		}
		Claims claims= (Claims) resultMsg1.getData();
		User sysUser = iUserService.getById(claims.getId());
		QueryWrapper<Message> queryWrapper = new QueryWrapper<Message>();
		queryWrapper.and(wrapper -> wrapper.eq("types", 0).or().eq("types", 1));
		queryWrapper.eq("froms", sysUser.getId());
		int count = iMessageService.count(queryWrapper);
		HashMap<String, Object> hashMap = new HashMap<String, Object>();
		hashMap.put("code", 0);
		hashMap.put("msg", "");
		hashMap.put("count", count);
		return hashMap;
	}
	/**
	 * 拒绝加好友
	 * 
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/refuseFriend")
	public HashMap<String, Object> refuseFriend(@RequestParam(value = "id") String id) {
		Message message1=new Message();
		message1.setId(Long.valueOf(id));
		message1.setTypes(2);
		message1.setReada(1);
		iMessageService.updateById(message1);
		HashMap<String, Object> hashMap = new HashMap<String, Object>();
		hashMap.put("code", 0);
		hashMap.put("msg", "已拒绝");
		return hashMap;
	}
	/**
	 * 分页查询自己的消息
	 * @param page
	 * @return
	 */
	@RequestMapping(value = "/listPage")
	public ResultTable<Messages> listPage(@RequestHeader("token") String token,@RequestParam(value = "page") String page) {
		ResultMsg resultMsg=new ResultMsg();
		ResultMsg resultMsg1= JwtUtils.validateJWT(token);
		if (!resultMsg1.isSuccess()){
			return null;
		}
		Claims claims= (Claims) resultMsg1.getData();
		User sysUser = iUserService.getById(claims.getId());
		ResultTable<Messages> resultTable=new ResultTable<Messages>();
		QueryWrapper<Message> queryWrapper = new QueryWrapper<Message>();
		queryWrapper.and(wrapper -> wrapper.eq("types", 0).or().eq("types", 1));
		queryWrapper.eq("froms", sysUser.getId());
		queryWrapper.orderByDesc("timea");
		IPage<Message> iPage = iMessageService.page(new Page<>(Integer.valueOf(page), Integer.valueOf(20)), queryWrapper);
		List<Message> list=iPage.getRecords();
		
		List<Messages> messageslist =new ArrayList<Messages>();
		for (Message message : list) {
			Messages messages=new Messages();
			messages.setContent(message.getContent());
			messages.setFrom(message.getFroms());
			messages.setId(message.getId());
			messages.setFrom_group(message.getFromGroup());
			messages.setHref(null);
			messages.setRead(message.getReada());
			messages.setTime(message.getTimea());
			messages.setType(message.getTypes());
			messages.setUid(message.getUid());
			messages.setRemark(message.getRemark());
			Long idLong=message.getUid();
			User user=iUserService.getById(idLong);
			if(user!=null) {
				user.setUpass("");
				user.setUname("");
				if (StringUtils.isNotBlank(user.getAvatar())) {
					user.setAvatar(url + user.getAvatar() + ".jpg");
				}
				messages.setUser(user);
			}
			messageslist.add(messages);
		}
		resultTable.setCount(iPage.getTotal());
		resultTable.setPages(page);
		//System.out.println(JSON.toJSONString(messageslist,true));
		resultTable.setData(messageslist);
		return resultTable;
	}
	
	
	/**
	 * 申请信息
	 *
	 * @return
	 */
	@RequestMapping(value = "/applyFriend")
	public ResultMsg add(@RequestHeader("token") String token,@RequestParam(value = "uid") String uid,
			@RequestParam(value = "gid") String gid, @RequestParam(value = "remark") String remark,
			@RequestParam(value = "type") String type) {
		ResultMsg resultMsg1= JwtUtils.validateJWT(token);
		if (!resultMsg1.isSuccess()){
			return null;
		}
		Claims claims= (Claims) resultMsg1.getData();
		User sysUser = iUserService.getById(claims.getId());
		Long idsLong=sysUser.getId();
		Message message = new Message();
		if (Integer.valueOf(type)==1) {
			//查询群是谁的
			Flock flock=iFlockService.getById(gid);
			message.setFroms(flock.getUserid());// 好友id
		}else {
			message.setFroms(Long.valueOf(uid));// 好友id
		}
		message.setUid(idsLong);
		
		message.setFromGroup(Integer.valueOf(gid));// 分组id或者群ID
		message.setRemark(remark);
		message.setTimea(LocalDateTime.now());
		message.setTypes(Integer.valueOf(type));
		ResultMsg resultMsg = new ResultMsg();
		// 申请之前检查自己是分组好友 或在群组
		if (Integer.valueOf(type)==0) {
			message.setContent("申请添加你为好友");
			if(isFirend(uid,sysUser.getId().toString())) {
				resultMsg.setMsg(ResultEnum.error_haoyou_failed.getMsg());
				return resultMsg;
			}
		}
		if (Integer.valueOf(type)==1) {
			//查询一下群名称
			Flock flock=iFlockService.getById(gid);
			message.setContent("申请添加 "+flock.getGroupname()+" 群");
			if(isFlock(uid,sysUser.getId().toString())) {
				resultMsg.setMsg(ResultEnum.error_qun_failed.getMsg());
				return resultMsg;
			}
		}
		boolean b = iMessageService.save(message);
		if (b) {
			resultMsg.setSuccess(true);
			resultMsg.setMsg(ResultEnum.sucess_create_failed.getMsg());
		} else {
			resultMsg.setMsg(ResultEnum.error_create_failed.getMsg());
		}

		return resultMsg;
	}

	/**
	 * 检查是否已经是好友
	 *
	 * @param uid
	 * @return
	 */
	public boolean isFirend(String uid, String fid) {
		int conut=iFriendsService.count(new QueryWrapper<Friends>().eq("friend", uid).eq("me", fid));
		if (conut==0) {
			return false;
		}
		return true;
	}
	/**
	 * 检查是否已经在群中
	 * 
	 * @param uid
	 * @return
	 */
	public boolean isFlock(String uid, String fid) {
		int conut=iFlockrefuserService.count(new QueryWrapper<Flockrefuser>().eq("uid", uid).eq("fid", fid));
		if (conut==0) {
			return false;
		}
		return true;
	}
}
